package net.risesoft.api.org;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;

import net.risesoft.entity.Y9Department;
import net.risesoft.entity.Y9Manager;
import net.risesoft.model.Manager;
import net.risesoft.service.org.Y9DepartmentService;
import net.risesoft.service.org.Y9ManagerService;
import net.risesoft.util.ModelConvertUtil;
import net.risesoft.y9.Y9LoginUserHolder;

/**
 * 三员服务组件
 *
 * @author dingzhaojun
 * @author qinman
 * @author mengjuhua
 * @date 2022/2/10
 * @since 9.6.0
 */
@Primary
@RestController
@RequestMapping(value = "/services/rest/manager", produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
public class ManagerApiImpl implements ManagerApi {

    private final Y9ManagerService y9ManagerService;
    private final Y9DepartmentService y9DepartmentService;

    /**
     * 根据id获得人员对象
     *
     * @param tenantId 租户id
     * @param userId 人员唯一标识
     * @return Manager 人员对象
     * @since 9.6.0
     */
    @Override
    @GetMapping("/getManager")
    public Manager getManager(@RequestParam String tenantId, @RequestParam String userId) {
        if (StringUtils.isNotBlank(tenantId)) {
            Y9LoginUserHolder.setTenantId(tenantId);
        }
        Y9Manager y9Manager = y9ManagerService.findById(userId);
        return ModelConvertUtil.convert(y9Manager, Manager.class);
    }

    /**
     * 判断是否为该部门的三员
     *
     * @param tenantId 租户id
     * @param userId 人员唯一标识
     * @param deptId 三员唯一标识
     * @return boolean 是否为该部门的三员
     * @since 9.6.0
     */
    @Override
    public boolean isDeptManager(@RequestParam String tenantId, @RequestParam String userId, @RequestParam String deptId) {
        if (StringUtils.isNotBlank(tenantId)) {
            Y9LoginUserHolder.setTenantId(tenantId);
        }
        Y9Manager y9Manager = y9ManagerService.findById(userId);
        Boolean tenantPerson = y9Manager.getGlobalManager();
        if (Boolean.TRUE.equals(tenantPerson)) {
            return true;
        } else {
            Y9Department orgDepartment = y9DepartmentService.getById(deptId);
            Y9Department managerDept = y9DepartmentService.getById(y9Manager.getParentId());
            String check = orgDepartment.getGuidPath();
            String mapping = managerDept.getGuidPath();
            if (check.contains(mapping) && (!check.equals(mapping))) {
                return true;
            }
            if (check.equals(mapping)) {
                return true;
            }
        }
        return false;
    }

}
